import React, { useState, useEffect } from 'react';
import {
  Tooltip,
  Table,
  Divider,
  Button,
  Modal,
  Popconfirm,
  Card,
  Space,
  Upload,
  message,
} from 'antd';
import {
  FormOutlined,
  PlusOutlined,
  PlusSquareOutlined,
  DeleteOutlined,
  SyncOutlined,
  ExportOutlined,
  ImportOutlined,
} from '@ant-design/icons';
import { FormattedMessage, useIntl } from 'umi';
import CateEdit from './cateedit';
import request from '@/utils/request';
import UploadUtil from '@/components/UploadUtil';
import { Scrollbars } from 'react-custom-scrollbars';

const ViewForm: React.FC<any> = (props) => {
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [dataSource, setDataSource] = useState([]);
  const [cateid, setCateid] = useState(0);
  const [parentCate, setParentCate] = useState({});
  const intl = useIntl();

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = () => {
    setLoading(true);
    request('/api/services/app/Category/GetTreeListAsync', {
      method: 'GET',
      params: { layout: props.layout },
    }).then((response) => {
      if (response) {
        if (response.success) {
          setLoading(false);
          setDataSource(response.result);
        }
      }
    });
  };

  const showModal = (val: any) => {
    setVisible(val);
  };

  const editCate = (cid: any) => {
    setCateid(cid);
    setParentCate({});
    showModal(true);
  };

  const addSubCate = (pid: any) => {
    setCateid(0);
    setParentCate(pid);
    showModal(true);
  };

  const addCate = () => {
    setCateid(0);
    setParentCate({});
    showModal(true);
  };

  const handleDelete = (val: any) => {
    setLoading(true);
    request('/api/services/app/Category/delete', {
      method: 'DELETE',
      params: { id: val },
    }).then((response) => {
      if (response) {
        if (response.success) {
          setLoading(false);
          fetchData();
        }
      }
    });
  };

  const handlerExport = async () => {
    const { layout } = props;
    const resp = await request('/api/Excel/ExportCate?layout=' + layout, {
      method: 'POST',
      responseType: 'blob',
    });
    const url = window.URL.createObjectURL(resp);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'ExportCate.xls';
    a.click();
  };

  const handlerImport = (info: any) => {
    if (info.file.status === 'done') {
      message.success(intl.formatMessage({ id: 'pages.importSuccess' }));
      fetchData();
    }
  };

  const columns = [
    {
      title: intl.formatMessage({ id: 'pages.categoryName' }),
      dataIndex: 'categoryName',
      key: 'categoryName',
    },
    {
      title: intl.formatMessage({ id: 'pages.categoryIndex' }),
      dataIndex: 'categoryIndex',
      key: 'categoryIndex',
    },
    {
      title: intl.formatMessage({ id: 'pages.action' }),
      key: 'action',
      render: (text: any, record: any) =>
        dataSource.length >= 1 ? (
          <span>
            <Tooltip placement="left" title={<FormattedMessage id="pages.edit" />}>
              <a onClick={() => editCate(record.id)}>
                <FormOutlined />
              </a>
            </Tooltip>
            <Divider type="vertical" />
            <Tooltip placement="bottom" title={<FormattedMessage id="pages.addChild" />}>
              <a onClick={() => addSubCate(record)}>
                <PlusSquareOutlined />
              </a>
            </Tooltip>
            <Divider type="vertical" />
            <Popconfirm
              title={<FormattedMessage id="pages.confirmDelete" />}
              onConfirm={() => handleDelete(record.id)}
            >
              <Tooltip placement="bottom" title={<FormattedMessage id="pages.delete" />}>
                <a>
                  <DeleteOutlined style={{ color: 'red' }} />
                </a>
              </Tooltip>
            </Popconfirm>
          </span>
        ) : null,
    },
  ];

  const rowSelection = {
    onChange: (selectedRowKeys: any, selectedRows: any) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    getCheckboxProps: (record: any) => ({
      name: record.name,
    }),
  };

  return (
    <div>
      <Card
        size={props.size}
        extra={
          <Space>
            <Tooltip title={<FormattedMessage id="pages.new" />}>
              <Button type="default" onClick={addCate} icon={<PlusOutlined />}>
                <span>
                  <FormattedMessage id="pages.new" />
                </span>
              </Button>
            </Tooltip>
            <Tooltip title={<FormattedMessage id="pages.refresh" />}>
              <Button type="default" onClick={fetchData} icon={<SyncOutlined />}>
                <span>
                  <FormattedMessage id="pages.refresh" />
                </span>
              </Button>
            </Tooltip>
            <Tooltip title={<FormattedMessage id="pages.export" />}>
              <Button type="primary" onClick={handlerExport} icon={<ExportOutlined />}>
                <span>
                  <FormattedMessage id="pages.export" />
                </span>
              </Button>
            </Tooltip>
            <Upload
              accept=".xls,.xlsx,application/vnd.ms-excel"
              name="file"
              action="/api/Excel/ImportCate"
              headers={{
                Authorization: UploadUtil.accessToken,
              }}
              beforeUpload={UploadUtil.checkExcel}
              showUploadList={false}
              onChange={handlerImport}
            >
              <Button icon={<ImportOutlined />}>
                <span>
                  <FormattedMessage id="pages.import" />
                </span>
              </Button>
            </Upload>
          </Space>
        }
      >
        <Scrollbars autoHide style={{ height: 300 }}>
          <Table
            rowKey={(record) => record.id}
            showHeader={false}
            columns={columns}
            dataSource={dataSource}
            loading={loading}
            pagination={false}
            size={props.size}
            rowSelection={rowSelection}
          />
        </Scrollbars>
        <Modal
          title={<FormattedMessage id="pages.categoryEdit" />}
          visible={visible}
          onCancel={() => showModal(false)}
          footer={null}
          destroyOnClose
        >
          <CateEdit
            RefreshData={fetchData}
            cateid={cateid}
            parentCate={parentCate}
            layout={props.layout}
          />
        </Modal>
      </Card>
    </div>
  );
};

export default ViewForm;
